package com.gulimall.guilimallmember.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.gulimall.common.utils.HttpUtils;
import com.gulimall.guilimallmember.dao.MemberLevelDao;
import com.gulimall.guilimallmember.entity.MemberLevelEntity;
import com.gulimall.guilimallmember.exception.PhoneExistException;
import com.gulimall.guilimallmember.exception.UserNameExistException;
import com.gulimall.guilimallmember.vo.MemberLoginVo;
import com.gulimall.guilimallmember.vo.MemberRegisterVo;
import com.gulimall.guilimallmember.vo.SocialUser;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gulimall.common.utils.PageUtils;
import com.gulimall.common.utils.Query;

import com.gulimall.guilimallmember.dao.MemberDao;
import com.gulimall.guilimallmember.entity.MemberEntity;
import com.gulimall.guilimallmember.service.MemberService;


@Service("memberService")
public class MemberServiceImpl extends ServiceImpl<MemberDao, MemberEntity> implements MemberService {
    @Autowired
    MemberLevelDao memberLevelDao;
    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<MemberEntity> page = this.page(
                new Query<MemberEntity>().getPage(params),
                new QueryWrapper<MemberEntity>()
        );

        return new PageUtils(page);
    }

    /**
     * 用户注册功能
     * @param registerVo
     */
    @Override
    public void register(MemberRegisterVo registerVo) {
        MemberDao memberDao = this.baseMapper;
        MemberEntity entity=new MemberEntity();
        //设置默认等级
        MemberLevelEntity levelEntity=memberLevelDao.getDefautLevel();
        entity.setLevelId(levelEntity.getId());

        //检查用户名和手机号是否唯一,为了让controller能感知异常，使用异常机制
        checkPhoneUnique(registerVo.getPhone());
        checkUseNameUnique(registerVo.getUserName());
        entity.setUsername(registerVo.getUserName());
        entity.setMobile(registerVo.getPhone());

        //密码要进行加密存储 md5盐值加密
        BCryptPasswordEncoder passwordEncoder=new BCryptPasswordEncoder();
        String encode = passwordEncoder.encode(registerVo.getPassword());
        entity.setPassword(encode);

        //其他默认信息
        entity.setCity("河北 邢台");
        entity.setCreateTime(new Date());
        entity.setStatus(0);
        entity.setNickname(registerVo.getUserName());
        entity.setBirth(new Date());
        entity.setEmail("xxx@gmail.com");
        entity.setGender(1);
        entity.setJob("JAVA");
        baseMapper.insert(entity);
    }

    @Override
    public void  checkPhoneUnique(String phone) throws PhoneExistException {
        Integer i = baseMapper.selectCount(new QueryWrapper<MemberEntity>().eq("mobile", phone));
        if(i>0){
            throw new PhoneExistException();
        }
    }


    @Override
    public void  checkUseNameUnique(String userName) throws UserNameExistException {
        Integer i = baseMapper.selectCount(new QueryWrapper<MemberEntity>().eq("username", userName));
        if(i>0){
            throw new UserNameExistException();
        }


    }

    /**
     * 用户登录功能
     *
     * @param vo
     * @return
     */
    @Override
    public MemberEntity login(MemberLoginVo vo) {
        String loginacct = vo.getLoginacct();
        String password = vo.getPassword();
        MemberDao memberDao = this.baseMapper;
        MemberEntity entity = memberDao.selectOne(new QueryWrapper<MemberEntity>().
                eq("username", loginacct).or().eq("mobile", loginacct));
        if(entity==null){
            return null;
        }
        else{
            String passwordDb = entity.getPassword();
            BCryptPasswordEncoder passwordEncoder=new BCryptPasswordEncoder();
            //密码匹配
            boolean matches = passwordEncoder.matches(password, passwordDb);
            if(matches){
                return entity;
            }
            else{
                return null;
            }
        }
    }

    /**
     * 社交登录
     * @param user
     * @return
     */
    @Override
    public MemberEntity socialLogin(SocialUser user) throws Exception {
        String name="";
        Map<String,String> map=new HashMap<>();
        map.put("access_token", user.getAccessToken());
        HttpResponse response = HttpUtils.doGet("https://gitee.com", "/api/v5/user", "get", new HashMap<String, String>(), map);
        if(response.getStatusLine().getStatusCode()==200){
            String s = EntityUtils.toString(response.getEntity());
            JSONObject jsonObject = JSON.parseObject(s);
            int id = (int)jsonObject.get("id");
            name = (String)jsonObject.get("name");
            user.setUid(id+"");
        }


        //登录和注册合并的逻辑
        String uid = user.getUid();
        //判断当前用户是否已经登录过系统
        MemberDao memberDao = this.baseMapper;
        MemberEntity member = memberDao.selectOne(new QueryWrapper<MemberEntity>().eq("social_uid", uid));
        if(member!=null){
            //这个用户已经注册过了
            MemberEntity memberEntity = new MemberEntity();
            memberEntity.setId(member.getId());
            memberEntity.setAccessToken(member.getAccessToken());
            memberEntity.setExpiresIn(member.getExpiresIn());
            memberDao.updateById(memberEntity);

            member.setAccessToken(user.getAccessToken());
            member.setExpiresIn(user.getRemindIn());
            return member;
        }
        else{
            MemberEntity register=new MemberEntity();
            register.setNickname(name);
            register.setSocialUid(user.getUid());
            register.setExpiresIn(String.valueOf(user.getExpiresIn()));
            register.setAccessToken(user.getAccessToken());
            memberDao.insert(register);
            return register;
        }
    }

}